<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="订单ID" prop="orderId">
        <el-input
            v-model="queryParams.orderId"
            placeholder="请输入订单ID"
            clearable
            @keyup.enter="handleQuery"
            style="width: 120px"
        />
      </el-form-item>
      <el-form-item label="名称" prop="orderName">
        <el-input
            v-model="queryParams.orderName"
            placeholder="请输入名称"
            clearable
            @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="完成时间" prop="deadTime" style="width: 308px">
        <el-date-picker clearable
                        v-model="queryParams.deadTime"
                        value-format="YYYY-MM-DD"
                        type="date"
                        @keyup.enter="handleQuery"
        ></el-date-picker>

      </el-form-item>
      <el-form-item label="状态" prop="orderStatus">
        <el-select v-model="queryParams.orderStatus" placeholder="选择状态" clearable style="width: 100px">
          <el-option
              v-for="dict in order_status"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="写手" prop="writerId" v-if="orderRoleWriter">
        <el-select v-model="queryParams.writerId" placeholder="选择写手" clearable style="width: 100px">
          <el-option v-for="item in userList"
                     :key="item.userId"
                     :label="item.nickName"
                     :value="item.userId">
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>
    <el-row :gutter="10" class="mb8">
      <!--新增按钮-->
      <el-col :span="1.5">
        <el-button
            type="primary"
            plain
            icon="Plus"
            @click="handleAdd"
            v-hasPermi="['manage:orders:add']"
        >新增
        </el-button>
      </el-col>
      <!--修改按钮-->
      <el-col :span="1.5">
        <el-button
            type="success"
            plain
            icon="Edit"
            :disabled="single"
            @click="handleUpdate"
            v-hasPermi="['manage:orders:edit']"
        >修改
        </el-button>
      </el-col>
      <!--删除按钮-->
      <el-col :span="1.5">
        <el-button
            type="danger"
            plain
            icon="Delete"
            :disabled="multiple"
            @click="handleDelete"
            v-hasPermi="['manage:orders:remove']"
        >删除
        </el-button>
      </el-col>
      <!--导出按钮-->
      <el-col :span="1.5">
        <el-button
            type="warning"
            plain
            icon="Download"
            @click="handleExport"
            v-hasPermi="['manage:orders:export']"
        >导出
        </el-button>
      </el-col>
      <!--稿件上传按钮-->
      <el-col :span="1.5">
        <el-button
            type="primary"
            plain
            :disabled="single"
            icon="Upload"
            @click="handleImport"
            v-hasPermi="['manage:orders:file:upload']"
        >稿件上传
        </el-button>
      </el-col>
      <!--分配按钮-->
      <el-col :span="1.5">
        <el-button
            type="primary"
            plain
            icon="User"
            :disabled="single"
            @click="handleOrderDistribute"
            v-hasPermi="['manage:orders:distribute']"
        >分配
        </el-button>
      </el-col>
      <!--解除按钮-->
      <el-col :span="1.5">
        <el-button
            type="primary"
            plain
            icon=""
            :disabled="single"
            @click="handleOrderUnBindWriter"
            v-hasPermi="['manage:order:unbind']">解除绑定
        </el-button>
      </el-col>
      <!--下载按钮-->
      <el-col :span="1.5">
        <el-button
            type="primary"
            plain
            icon="Download"
            :disabled="single"
            @click="handleDownFile"
            v-hasPermi="['manage:order:file:download']">稿件下载
        </el-button>
      </el-col>
      <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"/>
    </el-row>
    <!-- 表单 -->
    <el-table v-loading="loading" :data="ordersList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center"/>
      <!-- 序号 -->
      <el-table-column label="序号" align="center" width="50" prop="id">
        <template #default="scope">
          <span>{{ scope.$index + 1 }}</span>
        </template>
      </el-table-column>
      <el-table-column label="订单ID" align="center" prop="orderId" width="160">
        <template #default="scope">
          <el-popover placement="top-start" trigger="hover">
            <div v-html="scope.row.orderId"/>
            <template #reference>
              <el-tag>
                {{
                  scope.row.orderId.length > 15 ? scope.row.orderId.slice(0, 15) + '...' : scope.row.orderId
                }}
              </el-tag>
            </template>
          </el-popover>
        </template>
      </el-table-column>
      <el-table-column label="名称" align="center" prop="orderName" width="150">
        <template #default="scope">
          <el-popover placement="top-start" trigger="hover">
            <div v-html="scope.row.orderName"/>
            <template #reference>
              <el-tag>
                {{
                  scope.row.orderName.length > 15 ? scope.row.orderName.slice(0, 15) + '...' : scope.row.orderName
                }}
              </el-tag>
            </template>
          </el-popover>
        </template>
      </el-table-column>
      <el-table-column label="字数" align="center" prop="orderNum"/>
      <el-table-column label="完成时间" align="center" prop="deadTime" width="150">
        <template #default="scope">
          <span>{{ parseTime(scope.row.deadTime, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <!-- <el-table-column label="要求" align="center" prop="orderRequire" /> -->
      <!-- 要求字数太多的话只显示一部分，点击显示所有 -->
      <el-table-column label="要求" align="center" prop="orderRequire" width="180">
        <template #default="scope">
          <el-popover placement="top-start" trigger="hover" v-if="scope.row.orderRequire != '' || scope.row.orderRequire != null">
            <div v-html="scope.row.orderRequire"></div>
            <template #reference>
              <el-tag>
                {{
                   scope.row.orderRequire.length > 20 ? scope.row.orderRequire.slice(0, 20) + '...' : scope.row.orderRequire
                }}
              </el-tag>
            </template>
          </el-popover>
        </template>
      </el-table-column>
      <el-table-column label="写手" align="center" prop="writerName"/>
      <el-table-column label="状态" align="center" prop="orderStatus">
        <template #default="scope">
          <dict-tag :options="order_status" :value="scope.row.orderStatus">
          <span :style="getStatusStyle(scope.row.orderStatus)">
              {{ getLabel(scope.row.orderStatus) }}
            </span>
          </dict-tag>
          <!-- {{ console.log(scope.row.orderStatus) }} 调试行 -->
        </template>
      </el-table-column>
      <el-table-column label="金额" align="center" prop="orderMoney" v-if="orderRoleWriter"/>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width" v-if="orderRoleWriter">
        <template #default="scope">
          <el-tooltip content="修改" placement="top" v-if="scope.row.userId !== 1">
            <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)"
                       v-hasPermi="['manage:orders:edit']">
            </el-button>
          </el-tooltip>
          <el-tooltip content="删除" placement="top" v-if="scope.row.userId !== 1">
            <el-button link type="primary" icon="Delete" @click="handleDelete(scope.row)"
                       v-hasPermi="['manage:orders:remove']">
            </el-button>
          </el-tooltip>
        </template>
      </el-table-column>
    </el-table>
    <!-- 分页 -->
    <pagination
        v-show="total>0"
        :total="total"
        v-model:page="queryParams.pageNum"
        v-model:limit="queryParams.pageSize"
        @pagination="getList"
    />
    <!-- 添加或修改所有订单对话框 -->
    <el-dialog :title="title" v-model="open" width="500px" append-to-body>
      <el-form ref="ordersRef" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="订单ID" prop="orderId">
          <el-input v-model="form.orderId" placeholder="请输入订单ID" :disabled="orderIdDisabled"/>
        </el-form-item>
        <el-form-item label="名称" prop="orderName">
          <el-input v-model="form.orderName" placeholder="请输入名称"/>
        </el-form-item>
        <el-form-item label="字数" prop="orderNum">
          <el-input v-model="form.orderNum" placeholder="请输入字数"/>
        </el-form-item>
        <el-form-item label="完成时间" prop="deadTime">
          <el-date-picker clearable
                          v-model="form.deadTime"
                          type="date"
                          value-format="YYYY-MM-DD"
                          placeholder="请选择完成时间">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="要求" prop="orderRequire">
          <el-input v-model="form.orderRequire" type="textarea" placeholder="请输入内容"/>
        </el-form-item>
        <el-form-item label="金额" prop="orderMoney">
          <el-input v-model="form.orderMoney" placeholder="请输入金额"/>
        </el-form-item>
        <el-form-item label="状态" prop="orderStatus" v-if="orderStatusLoad">
          <el-select v-model="form.orderStatus" placeholder="选择状态" clearable style="width: 100px">
            <el-option
                v-for="dict in order_status"
                :key="dict.value"
                :label="dict.label"
                :value="dict.value"
            />
          </el-select>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
    <!-- 文件上传对话框   -->
    <el-dialog :title="upload.title" v-model="upload.open" width="600px" append-to-body>
      <el-form ref="ordersRef" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="订单名称" prop="orderName">
          <el-input v-model="form.orderName" :disabled="true" style="width: 220px" disabled/>
        </el-form-item>
        <el-form-item label="稿件类型" prop="orderType">
          <el-select v-model="fileType" style="width: auto" placeholder="请选择类型">
            <el-option
                v-for="item in upload.fileType"
                :key="item.dictValue"
                :label="item.dictLabel"
                :value="item.dictValue">
            </el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <el-upload
          ref="uploadRef"
          :limit="1"
          accept="*"
          :headers="upload.headers"
          :action="upload.url + '?orderId=' + upload.orderId + '&fileType=' + fileType"
          :disabled="upload.isUploading"
          :on-progress="handleFileUploadProgress"
          :on-success="handleFileSuccess"
          :auto-upload="false"
          drag
      >
        <el-icon class="el-icon--upload">
          <upload-filled/>
        </el-icon>
        <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>

      </el-upload>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitFileForm">确 定</el-button>
          <el-button @click="upload.open = false">取 消</el-button>
        </div>
      </template>
    </el-dialog>
    <!-- 订单分配 -->
    <el-dialog :title="distributeTitle" v-model="distributeOpen" width="500px" append-to-body>
      <el-form ref="ordersDistribute" :model="orderForm" label-width="80px">
        <el-form-item label="订单ID" prop="orderId" v-if="false">
          <el-input v-model="orderForm.orderId" :disabled="true"  placeholder="请输入订单ID"/>
        </el-form-item>
        <el-form-item label="订单名称" prop="orderName">
          <el-input v-model="orderForm.orderName" :disabled="true" placeholder="请输入名称"/>
        </el-form-item>
        <el-form-item label="角色" prop="roleKey">
          <el-radio-group v-model="orderForm.roleKey" @change="handleRadioChange">
            <el-radio v-model="orderForm.roleId" label="manager" border v-if="whetherNotManager">普通角色</el-radio>
            <el-radio v-model="orderForm.roleId" label="writer" border v-if="!whetherNotManager">写手</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="人员" prop="userId">
          <el-select v-model="orderForm.userId">
            <el-option v-for="item in userList"
                       :key="item.userId"
                       :label="item.nickName"
                       :value="item.userId"></el-option>
          </el-select>
        </el-form-item>

      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitWriter">确 定</el-button>
          <el-button @click="handleDistributeCancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
    <!-- 下载 -->
    <el-dialog :title="downFileTitle" v-model="downFileOpen" width="800px" height="500px" append-to-body
               style="overflow: auto">
      <el-table v-loading="orderFileLoading" :data="orderFileList"
                style="height: 500px; overflow: auto">

        <!-- 序号 -->
        <el-table-column label="序号" align="center" width="50" prop="fileId">
          <template #default="scope">
            <span>{{ scope.$index + 1 }}</span>
          </template>
        </el-table-column>
        <el-table-column label="订单编号" align="center" prop="orderId" width="180"/>
        <el-table-column label="文件Id" align="center" prop="fileId" v-if="false" width="180"/>
        <el-table-column label="稿件标识" align="center" prop="fileCode" v-if="false" width="180"/>
        <el-table-column label="稿件名称" align="center" prop="fileName" width="180"/>
        <el-table-column label="稿件类型" align="center" prop="fileType" width="120"/>
        <el-table-column label="完成时间" align="center" prop="createTime" width="160">
          <template #default="scope">
            <span>{{ parseTime(scope.row.createTime, '{y}-{m}-{d} {h}:{m}:{s}') }}</span>
          </template>
        </el-table-column>
        <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
          <template #default="scope">
            <el-button link type="primary" icon="Download" @click="handleOrderFileDown(scope.row)"
                       v-hasPermi="['manage:file:down:one']">下载
            </el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-dialog>
  </div>
</template>

<script setup name="Orders">
import {
  addOrders,
  delOrders,
  getOrders,
  listOrders,
  orderBindManagerWriter,
  orderUnBindWriter,
  updateOrders
} from "@/api/manage/orders";
import {getDicts} from "@/api/system/dict/data";
import {getInfo} from "@/api/login";
import {getToken} from "@/utils/auth";
import {checkAdminManager, findUserRoleKey, getLoginUserRole} from "@/api/system/user"
import { findOrderFile } from "@/api/manage/orderFile.js";


const {proxy} = getCurrentInstance();
const {order_status} = proxy.useDict('order_status');

const ordersList = ref([]);
const open = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);
const title = ref("");
const distributeTitle = ref("");
const distributeOpen = ref(false);
const fileType = ref('');
let userList = ref([]);
const whetherNotManager = ref(true);
const whetherNotDown = ref(true);
const orderIdDisabled = ref(false);

const downFileTitle = ref("");
const downFileOpen = ref(false);
const orderFileList = ref([]);
const orderFileLoading = ref(true);
const orderStatusLoad = ref(true)
const orderRoleWriter = ref(false)
const identity = ref("")

const data = reactive({
  form: {},
  orderForm: {},
  userQueryParams: {
    roleKey: null
  },
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    orderId: null,
    orderName: null,
    deadTime: null,
    orderStatus: null,
  },
  fileParams: {
    orderId: null
  },
  rules: {
    orderId: [
      {required: true, message: "订单ID不能为空", trigger: "blur"}
    ],
  },
  updateOrderStatusParams:{
    open: false,
    title: "",
    orderId: "",
    orderName: ""
  },
  orderStatusForm: {},
});

const {queryParams, form, rules, orderForm, userQueryParams, fileParams} = toRefs(data);


/** 查询所有订单列表 */
function getList() {
  loading.value = true;
  //获取当前登录者
  getLoginUserRole().then(response => {
    const roleKey = response.roleKey
    if (roleKey === 'writer') {
      orderRoleWriter.value = false
    }
    if (roleKey === 'manager' || roleKey === 'admin') {
      orderRoleWriter.value = true
      //获取所有写手
      const params = {'roleKey': "writer"}
      //获取写手信息
      findUserRoleKey(params).then(response => {
        userList = response.userList
      })
    }
  })
  listOrders(queryParams.value).then(response => {
    ordersList.value = response.rows;
    total.value = response.total;
    loading.value = false;
  });
}

// 取消按钮
function cancel() {
  open.value = false;
  reset();
}

// 表单重置
function reset() {
  form.value = {
    id: null,
    orderId: null,
    orderName: null,
    orderNum: null,
    deadTime: null,
    orderRequire: null,
    writerId: null,
    orderStatus: null,
    orderMoney: null,
  };
  proxy.resetForm("ordersRef");
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1;
  getList();
}

/** 重置按钮操作 */
function resetQuery() {
  // daterangeDeadTime.value = [];
  proxy.resetForm("queryRef");
  handleQuery();
}

// 多选框选中数据
function handleSelectionChange(selection) {
  ids.value = selection.map(item => item.id);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
}

/** 新增按钮操作 */
function handleAdd() {
  reset();
  open.value = true;
  title.value = "添加所有订单";
  orderIdDisabled.value = false;
  orderStatusLoad.value = false;
}

/** 修改按钮操作 */
function handleUpdate(row) {
  reset();
  const _ID = row.id || ids.value
  getOrders(_ID).then(response => {
    form.value = response.data;
    open.value = true;
    title.value = "修改所有订单";
    orderIdDisabled.value = true;
    orderStatusLoad.value = true;
  });
}

function orderDistributeReset() {
  orderForm.value = {
    id: null,
    orderId: null,
    orderName: null,
    roleKey: null,
    userId: null,
    writerId: null
  };
  proxy.resetForm("ordersDistribute");
}

/**
 * 分配
 * */
function handleOrderDistribute(row) {
  orderDistributeReset()
  const _ID = row.id || ids.value
  checkAdminManager().then(response => {
    whetherNotManager.value = response.data;
  })
  getOrders(_ID).then(response => {
    orderForm.value = response.data
  });
  distributeOpen.value = true
  distributeTitle.value = "订单分配"
}

/**
 * 分配取笑按钮
 */
function handleDistributeCancel() {
  distributeOpen.value = false
  reset();
}

function handleRadioChange(value) {
  userQueryParams.roleKey = value
  findUserRoleKey(userQueryParams).then(response => {
    userList = response.userList
  })
}

/** 提交按钮 */
function submitForm() {
  proxy.$refs["ordersRef"].validate(valid => {
    if (valid) {
      if (form.value.id != null) {
        updateOrders(form.value).then(response => {
          proxy.$modal.msgSuccess("修改成功");
          open.value = false;
          getList();
        });
      } else {
        addOrders(form.value).then(response => {
          proxy.$modal.msgSuccess("新增成功");
          open.value = false;
          getList();
        });
      }
    }
  });
}

/** 删除按钮操作 */
function handleDelete(row) {
  const _IDs = row.id || ids.value;
  proxy.$modal.confirm('是否确认删除所有订单编号为"' + _IDs + '"的数据项？').then(function () {
    return delOrders(_IDs);
  }).then(() => {
    getList();
    proxy.$modal.msgSuccess("删除成功");
  }).catch(() => {
  });
}

/** 导出按钮操作 */
function handleExport() {
  proxy.download('manage/orders/export', {
    ...queryParams.value
  }, `orders_${new Date().getTime()}.xlsx`)
}

function handleOrderFileDown(row) {
  const resource = row.fileCode
  proxy.$download.resourceNew(resource,false)
}

/**文件上传*/
function handleImport(row) {
  upload.title = "稿件上传";
  upload.open = true;
  const _ID = row.id || ids.value
  getOrders(_ID).then(response => {
    form.value = response.data;
    upload.orderId = response.data.orderId
    upload.orderName = form.value.orderName
  });

  getDicts('file_type').then(response => {
    upload.fileType = response.data
  })
}

// 获取状态样式
function getStatusStyle(orderStatus) {
  switch (orderStatus) {
    case 1:
      return 'color: black;';
    case 2:
      return 'color: orange;';
    case 3:
      return 'color: lightgreen;';
    case 4:
      return 'color: green;';
    case 5:
      return 'color: blue;';
    case 6:
      return 'color: gray;';
    default:
      return '';
  }
}

const upload = reactive({
  open: false,
  title: "",
  orderName: "",
  orderId: "",
  fileType: [],
  isUploading: false,
  headers: {Authorization: "Bearer " + getToken()},
  url: import.meta.env.VITE_APP_BASE_API + "/manage/file/import"
})

const handleFileUploadProgress = (event, file, fileList) => {
  upload.isUploading = true;
}

const handleFileSuccess = (response, file, fileList) => {
  upload.open = false;
  upload.isUploading = false;
  proxy.$refs["uploadRef"].handleRemove(file);
  proxy.$alert("<div style='overflow: auto;overflow-x: hidden;max-height: 70vh;padding: 10px 20px 0;'>" + response.msg + "</div>", "上传结果", {dangerouslyUseHTMLString: true});
  getList();
};

const userinfo = ref({});
// 页面加载时获取用户信息
onMounted(async () => {
      const response = await getInfo(); // 调用 getInfo 方法
      userinfo.value = response.user;   // 将返回的用户信息存储到 userinfo
      // console.log('User Info:', userinfo.value); // 打印用户信息用于调试
      getList(); // 获取订单列表
    }
)

/** 提交按钮 */
function submitFileForm() {
  proxy.$refs["uploadRef"].submit();
}

function submitWriter() {
  proxy.$refs["ordersDistribute"].validate(valid => {
    orderBindManagerWriter(orderForm.value).then(response => {
      proxy.$modal.msgSuccess("分配成功");
      distributeOpen.value = false;
      getList();
    })
  });
}

function handleOrderUnBindWriter(row) {

  const _IDs = row.orderId || ids.value;
  checkAdminManager().then(response => {
    whetherNotManager.value = response.data;
  })
  getOrders(_IDs).then(response => {
    const orderName = response.data.orderName
    const orderId = response.data.orderId
    identity.value = whetherNotManager.value ? "管理员" : "写手";
    const roleKey = whetherNotManager.value ? "manager" : "writer";
    const data = {"orderId": orderId, "roleKey": roleKey}
    const confirmMessage = '是否确认解除订单名称为"' + orderName + '"的数据项与' + identity.value+'的绑定?'
    proxy.$modal.confirm(confirmMessage).then(function () {
      return orderUnBindWriter(data);
    }).then(() => {
      getList();
      proxy.$modal.msgSuccess("解除绑定成功");
    }).catch(() => {
    });
  })
}

/**
 * 下载
 */
function handleDownFile(row) {
  const _IDs = row.orderId || ids.value;
  getOrders(_IDs).then(response => {
    const data = {"orderId": fileParams.orderId = response.data.orderId}
    findOrderFile(data).then(response => {
      orderFileList.value = response.data
      orderFileLoading.value = false
    })
  })
  downFileOpen.value = true
  downFileTitle.value = "稿件下载"
  checkAdminManager().then(response => {
    whetherNotManager.value = response.data;
    const roleKey = whetherNotManager ? "manager" : "writer";
    if (roleKey === 'writer') {
      whetherNotDown.value = false
    }else {
      whetherNotDown.value = true
    }
  })

}

</script>
